import {FANGAPI} from "../api/api.js";
import commonConstant from "../common/commonConstant.js";
import {userInfo} from "../user.js";
import {canvasUtil} from "../util/canvasUtil.js";
import {themeColor} from "../common/themeColor.js";
import {Game, renderChessDirectly, renderMap, startGame} from "../game/gaming.js";
import {globalData} from "../globalData/globalData.js";
import {getTouchTarget, isOnElement} from "../util/touchUtil.js";
import {clearElements, elements} from "../globalData/elements.js";
import {map1} from "../../maps/map1.js";
import {maps} from "../../maps/index.js";
import {computeSize, gameData, importMapData} from "../game/gameData.js";
import {BASE_URL, BASE_URL_SERVE, ws} from "../../adaptor/netConfig.js";

let selectedMap = maps[0]
export const roomInfo = {
    number: 0,
    player1: {
        id: 0,
        name: '',
        ready: true,
    },
    //房主
    roomer: 0,
    player2: {
        id: 0,
        name: '',
        ready: false,
    },
    //棋盘上棋子集合
    chessArrs: [],
    //游戏模式  1:经典模式  2:翻棋模式  3:四国模式
    model: 0,


}


export default class Room {
    constructor() {
        console.log('渲染区域并绑定事件');
        globalData.canvas.addEventListener('touchstart', this.touchHandler)
        // globalData.map = map1
    }

    renderRoom = () => {

        canvasUtil.clearCanvas()

        canvasUtil.drawText( `房间号:${roomInfo.number}`, 30, 50, themeColor.color2)
        canvasUtil.drawText( `玩家1:${roomInfo.player1.name}`, 30, 80, themeColor.color2)
        canvasUtil.drawText(`玩家2:${roomInfo.player2.name}`, 30, 110, themeColor.color2)

        if (userInfo.id === roomInfo.roomer) {
            //是房主
            // canvasUtil.drawRectElement('room_5', `开始`, 30, 150, 80, 20, themeColor.color1)
            // canvasUtil.drawText(`开始`, 30, 165, themeColor.color2)
            canvasUtil.drawButton('room_5', '开始游戏', 20, 160, 120, 30, themeColor.color2,themeColor.color1)
            canvasUtil.drawButton('invite', `邀请好友`, 160, 160, 120, 30, themeColor.color1,themeColor.color2)
        }

        // Object.assign(gameData, selectedMap)

        importMapData(selectedMap)
        computeSize(globalData.screenWidth / 2)
        gameData.startY = 500
        renderMap()
        renderChessDirectly()
        this.renderMapChoose()
        // canvas.addEventListener('touchstart', this.touchHandler)

    }

    renderMapChoose=()=>{
        let w = 150,h=30,startX = globalData.screenWidth / 2 +10,startY=500
        for (let i = 0;i<maps.length;i++) {
            let mapItem = maps[i]
            if(mapItem.id===selectedMap.id){
                canvasUtil.drawButton( 'map_'+mapItem.id,mapItem.name, startX, startY+i*h, w,h,themeColor.green2,themeColor.color2)
            }else {
                canvasUtil.drawButton( 'map_'+mapItem.id,mapItem.name, startX, startY+i*h, w,h,themeColor.color1,themeColor.color2)
            }
        }
    }


    newRoom = async () => {
        let res = await FANGAPI.room.createRoom({
            userId: userInfo.id,
            room: roomInfo
        })
        if (res.code === commonConstant.successCode) {
            this.updateRoomInfo(res.data)
            // this.renderRoom()
        }
    }

    joinRoom = async (roomNumber) => {

        let res = await FANGAPI.room.joinRoom(userInfo.id, roomNumber)
        if (res.code === commonConstant.successCode) {
            this.updateAndSendRoomInfo(res.data)

            this.renderRoom()
        }
    }
    updateAndSendRoomInfo = (_roomInfo) => {
        this.updateRoomInfo(_roomInfo)
        this.sendRoomInfo()
    }

    updateRoomInfo = (_roomInfo) => {
        Object.assign(roomInfo, _roomInfo)
        this.renderRoom()
    }

    sendRoomInfo = () => {
        console.log('synchronizedGameData', gameData);
        ws.sendMsg({
            cmd: commonConstant.CMD_UPDATE_ROOM_INFO,
            roomNumber: roomInfo.number,
            data: roomInfo
        })
        // wx.sendSocketMessage({
        //     data: JSON.stringify({
        //         cmd: commonConstant.CMD_UPDATE_ROOM_INFO,
        //         roomNumber: roomInfo.number,
        //         data: roomInfo
        //     })
        // })
    }



    touchHandler =  (e) => {
        e.preventDefault()
        const x = e.touches[0].clientX
        const y = e.touches[0].clientY
        console.log('touchstart room');

        let idArr = getTouchTarget(x, y)
        if (idArr.length !== 1) return;
        if (idArr[0] === 'room_5') {
            //点击了开始游戏
            console.log('开始游戏,清除监听');
            globalData.canvas.removeEventListener('touchstart', this.touchHandler)
            clearElements()
            new Game()
            startGame()
        } else if (idArr[0].startsWith('map')) {
            //点击了地图选择
            let mapArr = maps.filter(_m => 'map_' + _m.id === idArr[0])
            if (mapArr.length === 1) {
                selectedMap = mapArr[0]
                this.renderRoom()
            }
        } else if (idArr[0] === 'invite') {
            console.log('invite click');
            //点击了邀请好友
            alert(BASE_URL + '/index.html?roomNumber=' + roomInfo.number);
            // copyToClip(BASE_URL_SERVE + '/index.html?roomNumber=' + roomInfo.number,'成功')

        }


        // let ele = elements.get('room_5')
        // if (!ele) return
        // if (isOnElement(x, y, ele)) {
        //
        //     console.log('开始游戏,清除监听');
        //     canvas.removeEventListener('touchstart', this.touchHandler)
        //     clearElements()
        //     new Game()
        //     startGame(map1)
        // }
    }
}








